#!/usr/bin/env ./jshost


try{
if(!cnt)
	cnt=0;
}catch(e){cnt=0}


var onrequest=function(fd){
	write(fd,"Your fd="+fd+"\r\n");
	read(fd);
	for(var i=100;i<=110;++i){
		write(fd,"*"+i+"\r\n");
		sleep(200);
	}
//	sleep(200);
//	close(fd);
//	alert("close(fd)="+close(fd));
};



var zonrequest=function(c){
	var headers=[];
	var buf=[];
	var headers_sent=!1;
	var dirty=false;
	
	var flush=function(){
		if(!dirty)
			return;
		if(!headers_sent && headers.length>0) {
			fwrite(c, headers.join("\n")+"\n\n");
			headers_send=true;
			headers=[];
		}	
		if(buf.length>0) {
			fwrite(c, buf.join(""));
			buf=[];
		}
		fflush(c);
		dirty=false;
	};
	var header=function(x){
		headers[headers.length]=x;
		dirty=true;
	};
	var echo=function(x){
		buf[buf.length]=x;
		dirty=true;
		flush();
	};
	var close=function(){
		echo("\n");
		flush();
		fclose(c);
	};
	var x, h=[];
	while(x=fgets(c)){
		if(x=="\r\n")
			break;
		h[h.length]=x;
	}
	
	header("HTTP/1.1 200 OK");
	header("Content-Type:text/html; charset=UTF-8");
	echo("<h1>zhopa "+(cnt++)+"</h1>");
	echo("Headers recieved:<br><pre>");
	echo(h.join(""));
	echo("</pre>");
	echo("<div id=oOut style='font:normal bold 100px sans-serif'></div>\
	<script>\
		var oOut=document.getElementById('oOut');\
		var out=function(x){oOut.innerHTML=x};\
	</script>\
	");

	for(var i=10;i>=0;--i){
		echo("<script>out("+i+")</script>\n");
		flush(c);
		sleep(200);
	}

	close(c);
	return;

/*	
	var rec=function(n){
		if(n>=0){
			echo("<script>out("+n+")</script>\n");
			fflush(c);
			setTimeout(function(){rec(n-1)},200);
		} else {
			echo("<script>out('Жопа!')</script>\n");
			close();
		}
		
	};
	rec(20);
*/	
};




start_httpserver(false);
